package com.ys.controller.api.outer;

import com.ys.config.MyConfig;
import com.ys.service.purchase.Api1688Service;
import com.ys.util.dhecp.StringUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 1688接口
 * @author fxz
 *
 */
@CrossOrigin
@Controller
@RequestMapping("/api/outer/1688")
public class ApiOuter1688Controller {
	private static final Logger logger = LoggerFactory.getLogger(ApiOuter1688Controller.class);

	@Autowired
	private Api1688Service api1688Service;

	private BlockingQueue<Long> queue = new LinkedBlockingQueue<Long>(100);
	
	/**
	 * 1688授权回调
	 * @param code
	 */
	@RequestMapping("/authcallback")
	public void authCallBack(@RequestParam(required = true) String code, HttpServletResponse response) throws IOException {
		logger.info("1688授权回调开始!");
		if (StringUtils.isEmpty(code)){
			logger.error("获取1688授权回调时code值为空！");
		}else {
			R r = api1688Service.get1688Token(code);
			if (r.getCode() == R.Code.SUCCESS.value){
				logger.info("1688授权回调成功!");
				response.sendRedirect(MyConfig.getUrlDomain()+"/api/outer/1688/tokenauth?auth=yes");
			}else {
				logger.error("1688授权回调失败!失败原因如下:" + r.getMsg());
				response.sendRedirect(MyConfig.getUrlDomain()+"/api/outer/1688/tokenauth?auth=no");
			}
		}
	}

	/**
	 * 获取token回调地址
	 * @return
	 */
	@RequestMapping("/tokenauth")
	public  String tokenCallBack(@RequestParam(required = true) String auth, ModelMap mmap){
		if (StringUtils.isEmpty(auth)){
			auth = "no";
		}
		String message = "";
		if (auth.contains("yes")){
			message = "授权成功!";
		}else{
			message = "授权失败!";
		}
		mmap.put("message", message);
		return "purchase/api1688/tokenauth";
	}

	/**
	 * 接收1688消息 (回调地址需要通过1688后台设置)
	 */
	@RequestMapping("/pushMessage")
	@ResponseBody
	public String pushMessage(@RequestParam(required = true) Map<String, Object> params, HttpServletResponse response){
		R r = new R();
		try {
			if (queue.offer(System.currentTimeMillis(), 2, TimeUnit.SECONDS)) {
				queue.poll(0, TimeUnit.SECONDS);
				r = api1688Service.push1688Message(params);
			}

			if (r.getCode() == R.Code.SUCCESS.value){
				logger.info("ECP_API处理1688回调消息成功"+ r.getMsg());
				response.setStatus(200);
				return  "200";
			}else {
				logger.error("ECP_API处理1688回调消息出错，错误为" + r.getMsg());
				response.setStatus(500);
				return  "500";
			}
		}
		catch (Exception ex) {
			logger.error("ECP_API处理1688回调消息出错，错误为" + ex.getMessage());
			response.setStatus(500);
			return  "500";
		}
	}
}
